package com.guapi.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.guapi.annotation.SelfController;
import com.guapi.dao.Event;
import com.guapi.dao.ResponseData;
import com.guapi.dao.Task;
import com.guapi.dao.User;
import com.guapi.event.EventProducer;
import com.guapi.exception.SelfException;
import com.guapi.service.TaskService;
import com.guapi.service.UserService;
import com.guapi.util.KafkaConstant;
import com.guapi.util.request.SelfRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@SelfController
@RequestMapping("/task")
@ResponseBody
public class TaskController extends BaseController<Task> implements KafkaConstant {

    @Autowired
    private TaskService taskService;

    @Autowired
    private EventProducer eventProducer;

    @Autowired
    private UserService userService;

    /**
     * 获取任务列表
     *
     * @param request
     * @param data
     * @return
     */
    @RequestMapping("/list")
    public ResponseData list(HttpServletRequest request, @RequestBody Map data) {
        responseData = new ResponseData();
        List<Task> taskList;
        String taskName = "";
        String taskDesc = "";
        String state = (String) data.get("state");
        Map searchStr = (Map) data.get("searchStr");
        if (searchStr != null) {
            taskName = (String) searchStr.get("name");
            taskDesc = (String) searchStr.get("desc");
        }
        startPage(data);
        if (state != null) {
            //获取未完成，未被接单，未截止的task
            Task task = new Task();
            task.setFinished("1");
            task.setReceiver("");
            if (StrUtil.isAllEmpty(taskName, taskDesc)) {
                taskList = taskService.getByConditions(task);
            } else {
                if (StrUtil.isNotEmpty(taskName)) {
                    task.setTaskName(taskName);
                }
                if (StrUtil.isNotEmpty(taskDesc)) {
                    task.setTaskDesc(taskDesc);
                }
                taskList = taskService.getByFuzzy(task);
            }
        } else {
            if (StrUtil.isAllEmpty(taskName, taskDesc)) {
                taskList = taskService.list();
            } else {
                Task task = new Task();
                if (StrUtil.isNotEmpty(taskName)) {
                    task.setTaskName(taskName);
                }
                if (StrUtil.isNotEmpty(taskDesc)) {
                    task.setTaskDesc(taskDesc);
                }
                taskList = taskService.getByFuzzy(task);
            }
        }
        responseData.setRows(taskList);
        responseData.setSuccess(true);
        return responseData;
    }

    /**
     * 保存或更新任务
     *
     * @param request
     * @param task
     * @param judgeEdit
     * @return
     */
    @RequestMapping("save/{judgeEdit}")
    public ResponseData addTask(HttpServletRequest request, @RequestBody Task task, @PathVariable("judgeEdit") boolean judgeEdit) {
        SelfRequest selfRequest = createRequest(request);
        responseData = new ResponseData();
        User loginUser = getLoginUser();
        if (!judgeEdit) {
            String taskName = task.getTaskName();
            taskService.list().forEach(task1 -> {
                if (task1.getTaskName().equals(taskName)) {
                    throw new SelfException("想要添加的任务:" + taskName + "已存在");
                }
            });
        }
        try {
            if (task.getExpired() != null) {
                String expired = DateUtil.date(Long.parseLong(task.getExpired())).toString();
                task.setExpired(expired);
            }
            if (task.getCreateDate() == null) {
                task.setCreateBy(String.valueOf(loginUser.getId()));
            } else {
                task.setUpdateBy(String.valueOf(loginUser.getId()));
            }
            if (task.getPublisher() == null) {
                task.setPublisher(String.valueOf(loginUser.getId()));
            }
            if (taskService.saveOrUpdate(task)) {
                responseData.setData("task", task);
                responseData.setSuccess(true);
            }
        } catch (Exception e) {
            throw new SelfException("500", "添加任务失败，请稍后重试" + e.getMessage());
        }
        return responseData;
    }

    /**
     * 删除任务
     *
     * @param request
     * @param task
     * @return
     */
    @RequestMapping("/delete")
    public ResponseData deleteTask(HttpServletRequest request, @RequestBody Task task) {
        SelfRequest selfRequest = createRequest(request);
        responseData = new ResponseData();
        User loginUser = getLoginUser();

        task.setExpired(DateUtil.now());
        task.setUpdateBy(String.valueOf(loginUser.getId()));
        if (taskService.deleteEntity(task).equals(task)) {
            responseData.setSuccess(true);
            responseData.setData("role", task);
        }
        return responseData;
    }

    /**
     * 手动过期
     *
     * @param request
     * @param task
     * @return
     */
    @RequestMapping("/expired")
    public ResponseData expiredTask(HttpServletRequest request, @RequestBody Task task) {
        SelfRequest selfRequest = createRequest(request);
        responseData = new ResponseData();
        User loginUser = getLoginUser();

        task.setExpired(DateUtil.now());
        task.setDeadline(DateUtil.now());
        task.setEnable("1");
        task.setUpdateBy(String.valueOf(loginUser.getId()));
        if (taskService.saveOrUpdate(task)) {
            responseData.setData("task", task);
            responseData.setSuccess(true);
        }
        return responseData;
    }

    /**
     * 获取用户发布或者接收的任务
     *
     * @param request
     * @param user
     * @param judgePublish
     * @return
     */
    @RequestMapping("/myTask/{judge}")
    public ResponseData getUserPublish(HttpServletRequest request, @RequestBody User user, @PathVariable("judge") boolean judgePublish) {
        responseData = new ResponseData();
        Task task = new Task();
        if (ObjectUtil.isNull(user)) {
            user = getLoginUser();
        }
        if (judgePublish) {
            task.setPublisher(String.valueOf(user.getId()));
        } else {
            task.setReceiver(String.valueOf(user.getId()));
        }
        responseData.setRows(taskService.getByConditions(task));
        return responseData;
    }

    /**
     * 任务接受者取消任务
     *
     * @param request
     * @param task
     * @return
     */
    @RequestMapping("/cancel")
    public ResponseData cancelTask(HttpServletRequest request, @RequestBody Task task) {
        responseData = new ResponseData();
        task.setReceiver("");
        //违约取消任务，任务接收人设为空，向任务发布者发送消息通知
        Event event = new Event().setTopic(TOPIC_CANCEL_TASK)
                .setUserId(Integer.parseInt(task.getPublisher()))
                .setEntityType(SYSTEM_MESSAGE)
                .setData(DATA_KEY_CONTENT, String.format(
                        CANCEL_CONTENT,
                        task.getPublisher(),
                        task.getTaskName(),
                        getLoginUser().getUsername()));
        eventProducer.sendEvent(event);
        taskService.saveOrUpdate(task);
        responseData.setData("task", task);
        responseData.setSuccess(true);
        return responseData;
    }

    /**
     * 获取任务数
     *
     * @param request
     * @return
     */
    @RequestMapping("/count")
    public ResponseData countTask(HttpServletRequest request) {
        responseData = new ResponseData();
        User loginUser = getLoginUser();
        Task task = new Task();
        task.setPublisher(String.valueOf(loginUser.getId()));
        int publishCount = taskService.getCount(task);
        task = new Task();
        task.setReceiver(String.valueOf(loginUser.getId()));
        int receiveCount = taskService.getCount(task);
        responseData.setData("publishCount", publishCount);
        responseData.setData("receiveCount", receiveCount);
        responseData.setSuccess(true);
        return responseData;
    }

    /**
     * 接收任务
     *
     * @param request
     * @param task
     * @return
     */
    @RequestMapping("/accept")
    public ResponseData acceptTask(HttpServletRequest request, @RequestBody Task task) {
        Task one = taskService.getOne(task);
        responseData = new ResponseData();
        User loginUser = getLoginUser();
        if (!StrUtil.isEmpty(one.getReceiver())) {
            throw new SelfException("任务已被接收！");
        }
        one.setReceiver(String.valueOf(loginUser.getId()));

        Event event = new Event();
        String publishName = userService.getUsernameById(Integer.valueOf(one.getPublisher()));
        event.setTopic(TOPIC_ACCEPT_TASK)
                .setEntityType(SYSTEM_MESSAGE)
                .setUserId(Integer.parseInt(one.getPublisher()))
                .setData(DATA_KEY_CONTENT, String.format(
                        ACCEPT_CONTENT,
                        publishName,
                        one.getTaskName(),
                        loginUser.getUsername()));
        eventProducer.sendEvent(event);
        taskService.saveOrUpdate(one);
        responseData.setSuccess(true);
        responseData.setData("task", one);
        return responseData;
    }

    /**
     * 完成任务
     *
     * @param request
     * @param task
     * @return
     */
    @RequestMapping("/finish")
    public ResponseData finishTask(HttpServletRequest request, @RequestBody Task task) {
        responseData = new ResponseData();
        task.setUpdateBy(task.getReceiver());
        Event event = new Event();
        String publishName = userService.getUsernameById(Integer.valueOf(task.getPublisher()));
        event.setTopic(TOPIC_FINISH_TASK)
                .setEntityType(SYSTEM_MESSAGE)
                .setUserId(Integer.parseInt(task.getPublisher()))
                .setData(DATA_KEY_CONTENT, String.format(
                        FINISH_CONTENT,
                        publishName,
                        task.getTaskName(),
                        getLoginUser().getUsername()))
                .setData(DATA_KEY_TITLE,"在线接发单系统提示");
        eventProducer.sendEvent(event);
        taskService.updateById(task);
        responseData.setData("task", task);
        responseData.setSuccess(true);
        return responseData;
    }
}
